// 云函数入口文件
const cloud = require('wx-server-sdk')
const superagent = require('superagent')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.getNew) {
    //获取上课任务
    let data_cjcx = await superagent
      .get(`http://8.129.187.205:3000/wyu/jwxc/cjcx`)
      .then()
    let objData = JSON.parse(data_cjcx.text).data
    let finalData = []
    let allResults = {}

    let a = JSON.parse(objData.all)[0]
    allResults.address = a.tjz1
    allResults.grade = a.tjz2
    allResults.flunk = a.tjz3

    for (const key in objData.term) {
      await objData.term[key].forEach(item => { //数据清洗
        finalData.push({
          name: item.kcmc, //课程名称
          grade: item.cjjd, //绩点
          results: item.zcj, //成绩
          credit: item.xf, //学分
          term: item.xnxqdm //学期
        })
      })
    }

    try { //存入数据库
      await db.collection('user').where({
        id: wxContext.OPENID
      }).update({
        data: {
          cjcx: finalData,
          allResults
        },
      })

    } catch (e) {
      return e
    }


    return "ok"
  } else {
    let data = await db.collection('user').where({
      id: wxContext.OPENID
    }).get()
    return [data.data[0].allResults, data.data[0].cjcx]
  }
}